import time
import threading
from dataclasses import dataclass
from enum import Enum, auto
from typing import Optional, Dict, Any

class MCPStatus(Enum):
    STOPPED = auto()
    STARTING = auto()
    RUNNING = auto()
    STOPPING = auto()
    ERROR = auto()

@dataclass
class MCPConfig:
    name: str = "MCP Service"
    heartbeat_interval: float = 5.0
    max_workers: int = 4
    log_level: str = "INFO"

class MCPService:
    def __init__(self, config: Optional[MCPConfig] = None):
        self._status = MCPStatus.STOPPED
        self._config = config if config else MCPConfig()
        self._worker_threads = []
        self._lock = threading.Lock()
        self._stop_event = threading.Event()
    
    def start(self) -> bool:
        """启动MCP服务"""
        with self._lock:
            if self._status != MCPStatus.STOPPED:
                print("Service is not in STOPPED state")
                return False
            
            self._status = MCPStatus.STARTING
            print(f"Starting {self._config.name}...")
            
            # 重置停止事件
            self._stop_event.clear()
            
            # 启动工作线程
            for i in range(self._config.max_workers):
                thread = threading.Thread(
                    target=self._worker_loop,
                    name=f"Worker-{i+1}",
                    daemon=True
                )
                thread.start()
                self._worker_threads.append(thread)
            
            # 启动心跳线程
            self._heartbeat_thread = threading.Thread(
                target=self._heartbeat_loop,
                name="Heartbeat",
                daemon=True
            )
            self._heartbeat_thread.start()
            
            self._status = MCPStatus.RUNNING
            print(f"{self._config.name} started successfully")
            return True
    
    def stop(self) -> bool:
        """停止MCP服务"""
        with self._lock:
            if self._status != MCPStatus.RUNNING:
                print("Service is not running")
                return False
            
            self._status = MCPStatus.STOPPING
            print(f"Stopping {self._config.name}...")
            
            # 设置停止事件
            self._stop_event.set()
            
            # 等待工作线程结束
            for thread in self._worker_threads:
                thread.join(timeout=2.0)
            
            # 等待心跳线程结束
            self._heartbeat_thread.join(timeout=1.0)
            
            self._worker_threads = []
            self._status = MCPStatus.STOPPED
            print(f"{self._config.name} stopped successfully")
            return True
    
    def get_status(self) -> Dict[str, Any]:
        """获取服务状态"""
        with self._lock:
            return {
                "status": self._status.name,
                "config": self._config.__dict__,
                "workers": len(self._worker_threads),
                "is_running": self._status == MCPStatus.RUNNING
            }
    
    def update_config(self, new_config: MCPConfig) -> bool:
        """更新服务配置"""
        with self._lock:
            if self._status != MCPStatus.STOPPED:
                print("Can only update config when service is stopped")
                return False
            
            self._config = new_config
            print("Configuration updated successfully")
            return True
    
    def _worker_loop(self):
        """工作线程主循环"""
        thread_name = threading.current_thread().name
        print(f"{thread_name} started")
        
        while not self._stop_event.is_set():
            # 模拟工作
            print(f"{thread_name} is working...")
            time.sleep(1)
        
        print(f"{thread_name} stopped")
    
    def _heartbeat_loop(self):
        """心跳线程主循环"""
        print("Heartbeat started")
        
        while not self._stop_event.is_set():
            print("Heartbeat...")
            time.sleep(self._config.heartbeat_interval)
        
        print("Heartbeat stopped")

# 使用示例
if __name__ == "__main__":
    # 创建服务实例
    config = MCPConfig(name="My MCP Service", max_workers=2)
    mcp_service = MCPService(config)
    
    # 操作1: 启动服务
    mcp_service.start()
    
    # 操作2: 检查状态
    print("Service status:", mcp_service.get_status())
    
    # 让服务运行一段时间
    time.sleep(3)
    
    # 操作3: 更新配置 (需要先停止服务)
    mcp_service.stop()
    new_config = MCPConfig(name="Updated MCP Service", max_workers=3, log_level="DEBUG")
    mcp_service.update_config(new_config)
    
    # 再次启动
    mcp_service.start()
    time.sleep(2)
    
    # 操作4: 停止服务
    mcp_service.stop()
    
    # 最终状态
    print("Final status:", mcp_service.get_status())
